﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Contra
{
    abstract class AnimatedSprite
    {
        #region fields

        private int frameIndex;
        private double timeElapsed;
        private double timeToUpdate;

        protected Texture2D sTexture;
        protected string currentAnimation;
        protected myDirection currentDir = myDirection.none;
        protected Vector2 sDirection = Vector2.Zero;
        protected Vector2 bDirection = Vector2.Zero;
        protected enum myDirection { none, left, right };
        protected Dictionary<string, Rectangle[]> sAnimations = new Dictionary<string, Rectangle[]>();


        public Rectangle[] sRectangles
        {
            get;
            set;
        }

        
        
        public int characterFacing
        {
            get;
            set;
        }

        public Vector2 sPosition
        {
            get;
            set;
        }

        public Rectangle characterRec
        {
            get;
            set;

        }

        #endregion fields

        public AnimatedSprite(Vector2 position)
        {
            sPosition = position;
        }


        public virtual void UpDate(GameTime gameTime)
        {

            timeElapsed += gameTime.ElapsedGameTime.TotalSeconds;
                if (timeElapsed > timeToUpdate)
                {
                    timeElapsed -= timeToUpdate;

                    if (frameIndex < sAnimations[currentAnimation].Length - 1)
                    {
                        frameIndex++;
                    }
                    else
                    {
                        frameIndex = 0;
                    }
                }
        }

        public void AddAnimation(int frames, int yPos, int xStartFrame, string name, int width, int height, Vector2 offset)
        {
            Rectangle[] sRectangles = new Rectangle[frames];
            for (int i = 0; i < frames; i++)
            {
                sRectangles[i] = new Rectangle((i + xStartFrame) * width, yPos, width, height);
            }
            sAnimations.Add(name, sRectangles);
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            
            spriteBatch.Draw(sTexture, sPosition, sAnimations[currentAnimation][frameIndex], Color.White);

        }

        public void PlayAnimation(string name)
        {
            if (currentAnimation != name && currentDir == myDirection.none)
            {
                currentAnimation = name;
                frameIndex = 0;
            }
          
        }
        protected int FramesPerSecond
        {
            set { timeToUpdate = (1f / value); }
        }

    }
}
